﻿using NLog;
using Susha.Models.Pages;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;

namespace Susha.Models.Helpers
{
    public class ImageTools : IDisposable
    {
        private Int32 _mainWidth = 220;
        private Int32 _mainHeight = 135;
        private Double _coef;
        private PagesEnum page;

        private static Logger _logger = LogManager.GetCurrentClassLogger();

        private Int32 _width, _height, _widthOffset, _heightOffset;
        private HttpPostedFileBase _postedFile;
        private Image _incomingImage;
        
        public ImageTools(HttpPostedFileBase postedFile)
        {
            _postedFile = postedFile;
        }

        public String SaveFile(PagesEnum page, Int32 width, Int32 height)
        {
            this._mainWidth = width;
            this._mainHeight = height;
            _coef = (Double)_mainWidth / (Double)height;
            _incomingImage = Image.FromStream(_postedFile.InputStream, true, true);
            RecalculateMainParameters();
            String resultString = String.Format("{0}_{1}.{2}",
                                                    page.ToString(),
                                                    GetName(), 
                                                    GetExtention());
            Bitmap bitmap = Redraw();
            if (bitmap != null)
            {
                bitmap.Save(String.Format("{0}{1}", CommonTools.PATH_PHOTOS, resultString));
            }
            else
            {
                _logger.Error(String.Format("ImageTools.SaveFile(), Redraw вернул пустое значение: {0}", resultString));
            }
            return resultString;
        }

        private Bitmap Redraw()
        {
            Image image = (Image)(new Bitmap(_incomingImage, new Size(_width, _height)));
            Bitmap bitmap = new Bitmap(_mainWidth, _mainHeight);

            using (Graphics g = Graphics.FromImage((Image)bitmap))
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(image, _widthOffset, _heightOffset);
            }

            return bitmap;
        }

        private String GetName()
        {
            DateTime dt = DateTime.Now;
            return String.Format("{0}-{1}-{2}_{3}-{4}-{5}_{6}",
                                    dt.Year,
                                    dt.Month,
                                    dt.Day,
                                    dt.Hour,
                                    dt.Minute,
                                    dt.Second,
                                    Guid.NewGuid().ToString().Replace("-", String.Empty)
                );
        }

        private String GetExtention()
        {
            String result = String.Empty;

            switch (_postedFile.ContentType)
            {
                case "image/jpeg":
                    result = "jpg";
                    break;
                case "image/png":
                    result = "png";
                    break;
                case "image/gif":
                    result = "gif";
                    break;
                default:
                    _logger.Error(String.Format("ImageTools.GetExtention(): Unknown file format \"{0}\"", _postedFile.ContentType));
                    break;
            }

            return result;
        }

        private void RecalculateMainParameters()
        {
            Double coef = _incomingImage.Width / _incomingImage.Height;
            
            //Width of source img is larger than it must be
            if (coef > _coef)
            {
                RecalculateWidth();
            }
            //Height of source img is larger than it must be
            else if (coef < _coef)
            {
                RecalculateHeight();
            }
            else
            {
                _height = 135;
                _width = 220;
                _heightOffset = 0;
                _widthOffset = 0;
            }
        }

        private void RecalculateWidth()
        {
            _height = _mainHeight;
            _heightOffset = 0;
            Double coef = (Double)_incomingImage.Height / (Double)_mainHeight;
            _width = (Int32)(Math.Round((Decimal)(_incomingImage.Width / coef)));
            _widthOffset = -1 * (Int32)(Math.Round((Decimal)((_width - _mainWidth) / 2)));
        }

        private void RecalculateHeight()
        {
            _width = _mainWidth;
            _widthOffset = 0;
            Double coef = (Double)_incomingImage.Width /(Double) _mainWidth;
            _height = (Int32)(Math.Round((Decimal)(_incomingImage.Height / coef)));
            _heightOffset = -1 * (Int32)(Math.Round((Decimal)((_height - _mainHeight) / 2)));
        }

        public void Dispose() { }
    }
}